package aleksic.videogrid
{
	import com.greensock.events.LoaderEvent;
	import com.greensock.layout.ScaleMode;
	import com.greensock.loading.VideoLoader;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	public class Grid extends Sprite
	{
	 	private var vars:VideoGridFlashVars;
		
		public function Grid(vars:VideoGridFlashVars)
		{
			super();
			
			this.vars = vars;
			
			var i:int=0, 
				t:int = vars.files.length,
				cx:Number = 0, 
				cy:Number = 0;
			
			while (i<t) {
				var player:Player = new Player(vars);
				player.x = cx;
				player.y = cy;
				
				cx += vars.itemWidth + vars.itemDistance;
				if (numChildren % vars.gridColumns === vars.gridColumns-1) {
					cx = 0;
					cy += vars.itemHeight + vars.itemDistance;
				}
				if (vars.syncStart) {
					player.addEventListener(VideoLoader.VIDEO_BUFFER_FULL, handleVideoReady);
				}
				addChild(player);
				i++;
				
			}
			
			// draw transparent background so that width and height properties contain correct values  
			
			var gridWidth:Number = vars.gridColumns * vars.itemWidth + (vars.gridColumns-1) * vars.itemDistance;
			var gridHeight:Number = cy - vars.itemDistance;
			graphics.beginFill(0,0);
			graphics.drawRect(0,0,gridWidth,gridHeight);
			graphics.endFill();
			
		}
		
		protected function handleVideoReady(event:Event):void
		{
			var metaReadyCount:int = 0;
			var t:int = numChildren;
			while (t--) {
				var player:Player = getChildAt(t) as Player;
				if (player.loader && player.loader.metaData) {
					metaReadyCount++;
				}
			}
			if (metaReadyCount === numChildren) {
				play();
			}
		}
		
		public function unload():void
		{
			while(numChildren) {
				var player:Player = getChildAt(0) as Player;
				if (player) {
					player.loader.pauseVideo();
					player.loader.cancel();
					player.loader.dispose(true);
					removeChild(player);
				}
			}
		}
		
		public function play():void
		{
			var i:int=numChildren;
			while(i--) {
				var player:Player = getChildAt(i) as Player;
				if (player) {
					player.play();
				}
			}
		}
		public function pause():void
		{
			var i:int=numChildren;
			while(i--) {
				var player:Player = getChildAt(i) as Player;
				if (player) {
					player.pause();
				}
			}
		}
		 
		public function togglePlayback():void
		{
			var i:int=0, 
				t:int=numChildren;
			while(i<t) {
				var player:Player = getChildAt(i) as Player;
				player.toggle();
				i++;
			}
		}
	}
}